const cloud = require('wx-server-sdk');
const rp = require('request-promise');
// 初始化 cloud
cloud.init({
    // API 调用都保持和云函数当前所在环境一致
    env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database();
const _ = db.command;

/**
 * 这个示例将经自动鉴权过的小程序用户 openid 返回给小程序端
 * 
 * event 参数包含小程序端调用传入的 data
 * 调入参数 dakaCount studyCardCount nickName avatar
 * 
 */
exports.main = async(event, context) => {
    const response = {};
    // 发送请求生成图片
    const post_options = {
        method: 'POST',
        url: 'https://api.kuaihaibao.com/services/screenshot',
        body: {
            "template": "h9zuu2zh",
            "data": {
                "qrcode": "https://khb-sample.oss-cn-shanghai.aliyuncs.com/sample/sample_qr_0.png",
                "records": [{
                        "label": "累积打卡",
                        "number": 123,
                        "unit": "天"
                    },
                    {
                        "label": "学习卡片",
                        "number": 456,
                        "unit": "种"
                    },
                    {
                        "label": "行动力超过",
                        "number": "70",
                        "unit": "% 的同学"
                    }
                ],
                "tip": "刚刚完成了打卡",
                "slogan": "好好学习，天天向上",
                "companyColor": "#fff",
                "company": "脚丫英语",
                "brand": "脚丫英语",
                "backgroundImage": "https://khb-sample.oss-cn-shanghai.aliyuncs.com/sample/laptop.jpg",
                "backgroundColor": "#111",
                "user": {
                    "avatar": event.avatar,
                    "nickname": event.nickName
                }
            }
        },
        headers: {
            "Authorization": "Bearer eaeea7c2-b5c5-4c90-8abc-5b736dde558a",
            "Content-Type": "application/json; charset=utf-8"
        },
        json: true
    };
    try {
        const post_res = await rp(post_options);
        response.code = 200;
        response.body = post_res;
    } catch (err) {
        response.code = 500;
        response.error = err;
    }
    return response;
}